package main

import (
	"fmt"
	"math"
)

const (
	width, height = 600, 320
	cells         = 100
	xyrange       = 30.0
	xyscale       = width / 2 / xyrange
	zscale        = height * 0.4
	angle         = math.Pi / 6
)

var sin30, cos30 = math.Sin(angle), math.Cos(angle)

func main() {
	fmt.Printf("<svg xmlns='http://www.w3.org/2000/svg' "+
		"style='stroke: grey; fill: white; stroke-width: 0.7' "+
		"width='%d' height='%d'>", width, height)
	for i := 0; i < cells; i++ {
		for j := 0; j < cells; j++ {
			ax, ay := corner(i+1, j)
			bx, by := corner(i, j)
			cx, cy := corner(i, j+1)
			dx, dy := corner(i+1, j+1)
			x := xyrange * (float64(i)/cells - 0.5)
			y := xyrange * (float64(j)/cells - 0.5)
			color := calculateColor(f(x, y))
			fmt.Printf("<polygon points='%g,%g %g,%g %g,%g %g,%g' style='fill:%s;stroke-width:0.7;'/>\n", ax, ay, bx, by, cx, cy, dx, dy, color)
		}
	}
	fmt.Println("</svg>")
}

func corner(i, j int) (sx float64, sy float64) {
	x := xyrange * (float64(i)/cells - 0.5)
	y := xyrange * (float64(j)/cells - 0.5)

	z := f(x, y)

	sx = width/2 + (x-y)*cos30*xyscale
	sy = height/2 + (x+y)*sin30*xyscale - z*zscale
	return
}

// 计算颜色
func calculateColor(z float64) string {
	// 归一化z值到0-1之间
	if z > 0 {
		z = z / (2 * math.MaxFloat32)
	} else {
		z = z/(-2*math.MaxFloat32) + 1
	}

	// 使用归一化的z值作为颜色的混合比例 （从蓝到红）
	r := int((1 - z) * 255)
	g := 0
	b := int(z * 255)
	color := fmt.Sprintf("#%02x%02x%02x", r, g, b)
	return color
}
func f(x, y float64) float64 {
	r := math.Hypot(x, y) // distance from (0,0)
	result := math.Sin(r) / r
	if math.IsInf(result, 0) || math.IsNaN(result) {
		return 0
	}
	return result
}
